<template>
    <div class="page-userInfo">
        <!-- 导航栏部分 -->
        <div class="userInfo-nav">
            <Icon class="nav-icon" name="arrow-left" size="18" color="#fff" @click="back_btn"></Icon>
            <span class="nav-title">个人信息</span>
        </div>
        <!-- 用户头像部分 -->
        <div class="userInfo-avatar">
            <img :src="userInfo.avatar" alt="头像" title="头像" class="avatar-img" @click="ImagePreview ">
            <span class="avatar-tip" @click="updateAvatar">点击修改头像</span>
        </div>
        <!-- 用户信息表单区域 -->
        <div class="userInfo-form">
            <div class="form-item">
                <span class="item-tip">用户名</span>
                <span class="item-content" style="opacity: 0.5;">{{ userInfo.username }}</span>
            </div>
            <div class="form-item">
                <span class="item-tip">昵称</span>
                <input class="item-input" placeholder="请输入昵称" v-model="userInfo.nickname" />
            </div>
            <div class="form-item">
                <span class="item-tip">手机</span>
                <input class="item-input" placeholder="请输入手机号" v-model="userInfo.phone" />
            </div>
            <div class="form-item">
                <span class="item-tip">邮箱</span>
                <input class="item-input" placeholder="请输入邮箱" v-model="userInfo.email" />
            </div>
            <template v-if="isEditPassword">
                <div class="form-item">
                    <span class="item-tip">旧密码</span>
                    <input class="item-input" placeholder="请输入旧密码" v-model="userInfo.oldPassword" />
                </div>
                <div class="form-item">
                    <span class="item-tip">新密码</span>
                    <input class="item-input" placeholder="请输入新密码" v-model="userInfo.newPassword" />
                </div>
                <div class="form-item">
                    <span class="item-tip">确认密码</span>
                    <input class="item-input" placeholder="确认密码" v-model="userInfo.repassword" />
                </div>
            </template>
        </div>
        <!-- 修改密码? -->
        <div class="userInfo-edit-password-tip">
            <span class="tip-text" @click="changeIsEditPassword">{{ isEditPassword ? '退出修改密码' : '修改密码?' }}</span>
        </div>
        <!-- 按钮部分 -->
        <div class="userInfo-btns">
            <van-button class="btns-item" type="default" color="#27ba9b" @click="save_btn">保存</van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
//引入vue组合式api
import { ref, reactive, onMounted } from "vue";
//引入vant4组件
import { Icon, Button as VanButton, showSuccessToast, showToast, showImagePreview } from "vant";
//引入vue-router
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
//@ts-ignore引入用户仓库
import { useUserStore } from "@/store/userStore.ts";
const userStore = useUserStore();
//@ts-ignore引入请求api
import { reqUserInfo, reqUpdateUserInfo, reqUpdateAvatar } from "@/api/user/index.ts";

//用户信息表单
const userInfo = reactive({
    id:0,  //用户id
    avatar:"",  //头像
    username:"",  //用户名
    nickname:"",  //用户昵称
    phone:"",  //手机
    email:"",  //邮箱
    pwd:"",  //password
    oldPassword:"",  //旧密码
    newPassword:"",  //新密码
    repassword:""  //确认密码
})
//修改密码模式
let isEditPassword = ref(false);

//获取平台会员用户信息
const getUserInfo = async () => {
    let userinfo = userStore.userInfo.username || (JSON.parse(localStorage.getItem('userInfo')).username) || (JSON.parse(localStorage.getItem('username')));
    if(userinfo === undefined || userinfo === "") return showToast("未知错误,请重新登录!");
    //发请求获取用户信息
    let res = await reqUserInfo(userinfo);
    if(res.code === 200){
        userInfo.id = res.result.id;
        userInfo.avatar = res.result.avatar;
        userInfo.username = res.result.username;
        userInfo.nickname = res.result.nickname;
        userInfo.phone = res.result.phone;
        userInfo.email = res.result.email;
        userInfo.pwd = res.result.password;
        showToast("用户信息获取成功!");
    }
    console.log('获取用户信息api',res);
}

//返回上一页
function back_btn () {
    router.go(-1);
}
//修改密码、退出修该密码
function changeIsEditPassword () {
    isEditPassword.value = !isEditPassword.value;
}
//点击修改头像按钮
function updateAvatar () {
    console.log('修改头像');
    let tempAvatar:any = document.querySelector(".userInfo-avatar");
    let tempInput = document.createElement("input");
    tempInput.type = "file";
    //tempInput.name = 'multiple';
    tempInput.style.display = "none";
    tempAvatar.appendChild(tempInput);
    tempInput.click();
    //选择了文件
    tempInput.onchange = async () => {
        const file = tempInput.files[0];
        const fileName = tempInput.files[0].name;
        //对选择的文件进行判断
        if(file.size > 2*1024*1024){
            return showToast("选择的文件超过2M!");
        }
        const formData = new FormData();
        formData.append('multipartFile',file);  //将文件对象转为Blob对象
        const url = URL.createObjectURL(file);  //将文件在内存中生成一个临时路径
        //userInfo.avatar = url;  //内存中的临时路径赋值给img
        //console.log(formData);
        //console.log(url);
        let res:any = await reqUpdateAvatar(formData);
        if(res.code === 200){
            //头像上传成功
            userInfo.avatar = res.data[0];
        }
        console.log('文件上传(二进制blob)api',res);
    }
}
//点击头像实现预览
function ImagePreview () {
    showImagePreview({
        images: [userInfo.avatar],
        closeable: true
    });
} 
//保存按钮
async function save_btn () {
    //参数准备
    const info = {username:userInfo.username,nickname:userInfo.nickname,email:userInfo.email,phone:userInfo.phone,avatar:userInfo.avatar};
    if(isEditPassword.value){
        if(userInfo.oldPassword.trim() === '' || userInfo.newPassword.trim() === '' || userInfo.repassword.trim() === '')return showToast("请将表单信息填写完整!");
        if(userInfo.pwd !== userInfo.oldPassword) return showToast("原密码输入错误,请重试!");
        if(userInfo.newPassword !== userInfo.repassword) return showToast("两次密码输入不一致!");
        if(userInfo.newPassword.length < 6) return showToast("密码不能少于六位!");
        info.password = userInfo.newPassword;
    }
    //对参数进行简单校验
    if(userInfo.nickname.trim() === '' || userInfo.phone.trim() === '' || userInfo.email.trim() === '') return showToast("请求表单信息填写完整!");
    if(isNaN(Number(userInfo.phone)) || userInfo.phone.length !== 11) return showToast("请输入正确的手机号码!");
    //发请求更新用户信息
    let res = await reqUpdateUserInfo(info);
    if(res.code === 200){
        showSuccessToast("用户信息更新成功!");
        //延时1s重新请求用户信息
        setTimeout(() => {
            getUserInfo();
        },1000)
    }
    console.log('用户信息修改api',res);
}

//vue生命周期
onMounted(() => {
    //获取用户信息
    getUserInfo();
})

</script>

<style lang="less" scoped>
.page-userInfo{
    width: 375px;
    height: 100vh;
    background: #eff2f5;
    /**导航栏部分 */
    .userInfo-nav{
        width: 100%;
        height: 50px;
        padding: 15px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        text-align: center;
        background: #00c5a2;
        .nav-title{
            font-size: 18px;
            color: #fff;
        }
        .nav-title{
            position: relative;
            left: 45%;
            transform: translateX(-50%);
        }
    }
    /**用户头像部分 */
    .userInfo-avatar{
        width: 375px;
        height: 150px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #00c5a2;
        .avatar-img{
            width: 80px;
            height: 80px;
            margin-bottom: 10px;
            border-radius: 50%;
        }
        .avatar-tip{
            font-size: 12px;
            color: #fff;
        }
    }
    /**用户信息表单区域 */
    .userInfo-form{
        width: 360px;
        margin: 10px auto;
        padding:8px;
        background: #fff;
        border-radius: 5px;
        .form-item{
            width: 100%;
            height: 45px;
            border-bottom: 1px solid #b3fbee;
            display: flex;
            align-items: center;
            .item-tip{
                flex: 1;
                font-size: 14px;
                color: #9195a3;
            }
            .item-content{
                flex:3;
                font-size: 14px;
                color: #000;
            }
            .item-input{
                flex:3;
                height: 30px;
                border: none;
                font-size: 14px;
                
                &::placeholder{
                    font-size: 12px;
                    color: #c7c8cc;
                }
            }
        }
        :last-child{
            border-bottom: none;
        }
    }
    /**修改密码提示 */
    .userInfo-edit-password-tip{
        width: 375px;
        height: 20px;
        padding: 0 20px;
        box-sizing: border-box;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .tip-text{
            font-size: 12px;
            color: #5581df;
        }
    }
    /**按钮部分 */
    .userInfo-btns{
        width: 375px;
        margin: 20px 0;
        display: flex;
        justify-content: center;
        .btns-item{
            width: 360px;
        }
    }
}
</style>